<template>
  <div
    style="
      display: flex;
      justify-content: center;
      align-items: center;
      width: 90%;
    "
  >
    <a-form :model="form" :style="{ width: '860px' }">
      <a-form-item field="title" label="标题">
        <a-input v-model="form.title" placeholder="请输入题目标题" />
      </a-form-item>

      <a-form-item field="tags" label="标签">
        <a-input-tag v-model="form.tags" placeholder="请选择标签" allow-clear />
      </a-form-item>

      <a-form-item field="content" label="题目内容">
        <MyMDEditor :value="form.content" :handle-change="onContentChange" />
      </a-form-item>

      <a-form-item field="answer" label="题解">
        <MyMDEditor :value="form.answer" :handle-change="onAnswerChange" />
      </a-form-item>

      <a-form-item label="题目配置" :content-flex="false" :merge-props="false">
        <a-space direction="vertical" fill>
          <a-form-item field="judgeConfig.timeLimit" label="时间限制">
            <a-input-number
              v-model="form.judgeConfig.timeLimit"
              :style="{ width: '360px' }"
              placeholder="0~999（单位ms）"
              class="input-demo"
              :min="0"
              :max="1000"
            >
              <template #append> 毫秒</template>
            </a-input-number>
          </a-form-item>
          <a-form-item field="judgeConfig.memoryLimit" label="空间限制">
            <a-input-number
              v-model="form.judgeConfig.memoryLimit"
              :style="{ width: '360px' }"
              placeholder="0~999（单位MB）"
              class="input-demo"
              :min="0"
              :max="1000"
            >
              <template #append> 兆</template>
            </a-input-number>
          </a-form-item>
        </a-space>
      </a-form-item>

      <a-form-item
        label="测试用例配置"
        :content-flex="false"
        :merge-props="false"
      >
        <a-space direction="vertical" fill>
          <a-form-item
            v-for="(judgeCaseItem, index) of form.judgeCase"
            :key="index"
            no-style
          >
            <a-space direction="vertical" style="min-width: 500px">
              <a-form-item
                :field="`form.judgeCase[${index}].input`"
                :label="`输入用例-${index}`"
                :key="index"
              >
                <a-input
                  v-model="judgeCaseItem.input"
                  placeholder="请输入测试输入用例"
                />
              </a-form-item>
              <a-form-item
                :field="`form.judgeCase[${index}].output`"
                :label="`输出用例-${index}`"
                :key="index"
              >
                <a-input
                  v-model="judgeCaseItem.output"
                  placeholder="请输入测试输出用例"
                />
              </a-form-item>
              <a-button status="danger" @click="handleDelete(index)">
                删除
              </a-button>
            </a-space>
          </a-form-item>
        </a-space>
      </a-form-item>

      <a-form-item>
        <div style="margin-top: 32px">
          <a-button @click="handleAdd" type="outline" status="success"
            >新增测试用例
          </a-button>
        </div>
      </a-form-item>

      <a-form-item>
        <a-button type="primary" style="min-width: 200px" @click="doSubmit"
          >{{ submitOrUpdateButon.submitOrUpdate }}
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import MyMDEditor from "@/components/MyMDEditor.vue";
import { useRoute, useRouter } from "vue-router";

import {
  OjQuestionControllerService,
  UserLoginRequest,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";

let form = ref({
  title: "",
  tags: [],
  answer: "",
  content: "",
  judgeConfig: {
    memoryLimit: "",
    stackLimit: "100",
    timeLimit: "",
  },
  judgeCase: [
    {
      input: "",
      output: "",
    },
  ],
});

const route = useRoute();
const router = useRouter();

const submitOrUpdateButon = reactive({
  submitOrUpdate: route.query.id ? "点击修改" : "点击创建",
});

/**
 * 新增判题用例
 */
const handleAdd = () => {
  form.value.judgeCase.push({
    input: "",
    output: "",
  });
};

/**
 * 删除判题用例
 */
const handleDelete = (index: number) => {
  form.value.judgeCase.splice(index, 1);
};

/**
 * 提交保存题目信息
 */
const doSubmit = async () => {
  console.log(form.value);
  const id = route.query.id;
  if (!id) {
    const res = await QuestionControllerService.addQuestionUsingPost(
      form.value
    );
    if (res.code === 0) {
      message.success("题目创建成功");
      router.push({
        path: "/",
        replace: true,
      });
    } else {
      message.error("创建失败", res.message);
    }
  } else {
    const res = await OjQuestionControllerService.editQuestionUsingPost(
      form.value
    );
    if (res.code === 0) {
      message.success("题目修改成功");
      router.push({
        path: "/",
        replace: true,
      });
    } else {
      message.error("修改失败", res.message);
    }
  }
};

/**
 * 绑定写入题目内容
 * @param value
 */
const onContentChange = (value: string) => {
  form.value.content = value;
};

/**
 * 绑定写入题解内容
 * @param value
 */
const onAnswerChange = (value: string) => {
  form.value.answer = value;
};

onMounted(() => {
  loadData();
});

/**
 * 判定修改还是新增
 */
const loadData = async () => {
  const id = route.query.id;
  if (!id) {
    return;
  }
  const res = await QuestionControllerService.getQuestionByIdUsingGet(
    id as any
  );
  if (res.code === 0) {
    console.log("回显题目", res);
    form.value = res.data as any;
    // json 转 js 对象
    if (!form.value.judgeCase) {
      form.value.judgeCase = [
        {
          input: "",
          output: "",
        },
      ];
    } else {
      form.value.judgeCase = JSON.parse(form.value.judgeCase as any);
    }
    if (!form.value.judgeConfig) {
      form.value.judgeConfig = {
        memoryLimit: "1000",
        stackLimit: "1000",
        timeLimit: "1000",
      };
    } else {
      form.value.judgeConfig = JSON.parse(form.value.judgeConfig as any);
    }
    if (!form.value.tags) {
      form.value.tags = [];
    } else {
      form.value.tags = JSON.parse(form.value.tags as any);
    }
  } else {
    message.error("加载失败，" + res.message);
  }
};
</script>

<style scoped></style>
